/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package forumgui;

import GuiClient.TelnetClient;
import TamirsGui.CreateMsgToServer;
import TamirsGui.GuiMessage;
import TamirsGui.GuiMessage.MessageSubType;
import TamirsGui.GuiMsg;
import java.awt.HeadlessException;
import java.awt.event.MouseEvent;
import java.util.Stack;
import java.util.Vector;
import javax.swing.JOptionPane;

/**
 *
 * @author Tamir
 */
public class Forum extends javax.swing.JFrame {
    private String tempUserName;
    /**
     * Creates new form Forum
     */
    public Forum(TelnetClient client,CreateMsgToServer protocol) {
        initComponents();
        this.protocol = protocol;
        this.sendMsgToServer = client;
        logoutButton.setVisible(false);
        forumMsgsMainPane = new Vector<GuiMessage>();
        popupMsgs = new Vector<GuiMessage>();
        currentPath = new Stack<Vector<String>>();
        isGuest = true;
        userName ="guest";
        this.tempUserName = "guest";
        this.addThreadButton.setVisible(false);
        this.addModeratorButton.setVisible(false);
        this.removeModeratorButton.setVisible(false);
        this.addSubForumButton.setVisible(false);
        this.removeSubForumButton.setVisible(false);
         this.msgsForUserButton.setVisible(false);
         this.totalMsgsButton.setVisible(false);
         this.changeAdminButton.setVisible(false);
         this.numOfConnectionButton.setVisible(false);
    }

    private void changeFromMemberToGuest() {
      
        this.logoutButton.setVisible(false);
        this.loginButton.setVisible(true);
        this.registerButton.setVisible(true);
        isGuest = true;
        userName = "guest";
        this.addThreadButton.setVisible(false);
        this.addModeratorButton.setVisible(false);
        this.removeModeratorButton.setVisible(false);
        this.addSubForumButton.setVisible(false);
        this.removeSubForumButton.setVisible(false);
         this.msgsForUserButton.setVisible(false);
         this.totalMsgsButton.setVisible(false);
         this.changeAdminButton.setVisible(false);
         this.numOfConnectionButton.setVisible(false);
        
    }

    private void changeLookFromGuestToMember() {
        this.loginButton.setVisible(false);
        this.logoutButton.setVisible(true);
        this.registerButton.setVisible(false);
    }

    private void createAddOrRemoveModerator(boolean isAdd) throws HeadlessException {
        GuiMessage msg = (GuiMessage)this.listOfObjects.getSelectedValue();
       if (msg != null)
       {
            Vector<String> path = new Vector<String>();
            path.add(msg.getMessageId());
            if (isAdd)
            {
                this.createNewSenderThread(protocol.getModeratorsCandidateMsg(userName, path));
            }
            else
            {
                 this.createNewSenderThread(protocol.getModerators(userName, path));
            }
       }
       else
       {
            JOptionPane.showMessageDialog(this, "you must select from the list", "error", JOptionPane.WARNING_MESSAGE);
       }
    }

    private void createNewSenderThread(String msg) {
        System.out.println("the message i send is "+msg);
        new Thread(new SenderThread(sendMsgToServer, msg)).start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        BackButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        loginButton = new javax.swing.JButton();
        registerButton = new javax.swing.JButton();
        msgPopUpPane = new java.awt.ScrollPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        listPopupMsgs = new javax.swing.JList();
        mainForumPane = new java.awt.ScrollPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        listOfObjects = new javax.swing.JList();
        logoutButton = new javax.swing.JButton();
        goButton = new javax.swing.JButton();
        viewButton = new javax.swing.JButton();
        addThreadButton = new javax.swing.JButton();
        addModeratorButton = new javax.swing.JButton();
        removeModeratorButton = new javax.swing.JToggleButton();
        addSubForumButton = new javax.swing.JButton();
        removeSubForumButton = new javax.swing.JButton();
        totalMsgsButton = new javax.swing.JButton();
        msgsForUserButton = new javax.swing.JButton();
        changeAdminButton = new javax.swing.JButton();
        numOfConnectionButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        BackButton.setText("Back");
        BackButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BackButtonActionPerformed(evt);
            }
        });

        exitButton.setText("Exit");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        loginButton.setText("Login");
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });

        registerButton.setText("register");
        registerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                registerButtonActionPerformed(evt);
            }
        });

        listPopupMsgs.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, msgPopUpPane, org.jdesktop.beansbinding.ObjectProperty.create(), listPopupMsgs, org.jdesktop.beansbinding.BeanProperty.create("elements"));
        bindingGroup.addBinding(binding);

        listPopupMsgs.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listPopupMsgsMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(listPopupMsgs);

        msgPopUpPane.add(jScrollPane2);

        listOfObjects.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listOfObjects.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listOfObjectsMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(listOfObjects);

        mainForumPane.add(jScrollPane1);

        logoutButton.setText("logout");
        logoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoutButtonActionPerformed(evt);
            }
        });

        goButton.setText("GO");
        goButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                goButtonActionPerformed(evt);
            }
        });

        viewButton.setText("View");
        viewButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewButtonActionPerformed(evt);
            }
        });

        addThreadButton.setText("add Thraed");
        addThreadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addThreadButtonActionPerformed(evt);
            }
        });

        addModeratorButton.setText("Add moderator");
        addModeratorButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addModeratorButtonActionPerformed(evt);
            }
        });

        removeModeratorButton.setText("remove moderator");
        removeModeratorButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeModeratorButtonActionPerformed(evt);
            }
        });

        addSubForumButton.setText("add subForum");
        addSubForumButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addSubForumButtonActionPerformed(evt);
            }
        });

        removeSubForumButton.setText("remove subForum");
        removeSubForumButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeSubForumButtonActionPerformed(evt);
            }
        });

        totalMsgsButton.setText("totalMsgs");
        totalMsgsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                totalMsgsButtonActionPerformed(evt);
            }
        });

        msgsForUserButton.setText("msgsForUser");
        msgsForUserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                msgsForUserButtonActionPerformed(evt);
            }
        });

        changeAdminButton.setText("changeAdmin");
        changeAdminButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeAdminButtonActionPerformed(evt);
            }
        });

        numOfConnectionButton.setText("numOfConnection");
        numOfConnectionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                numOfConnectionButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(viewButton, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                            .addComponent(msgPopUpPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(addSubForumButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(removeSubForumButton)
                                .addGap(11, 11, 11)
                                .addComponent(BackButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(addThreadButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(goButton, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(msgsForUserButton)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(changeAdminButton)
                                        .addComponent(totalMsgsButton))
                                    .addComponent(numOfConnectionButton))
                                .addGap(61, 61, 61)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(exitButton)
                                        .addGap(35, 35, 35)
                                        .addComponent(registerButton)
                                        .addGap(31, 31, 31)
                                        .addComponent(logoutButton)
                                        .addGap(18, 18, 18)
                                        .addComponent(loginButton))
                                    .addComponent(mainForumPane, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addModeratorButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(removeModeratorButton)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loginButton)
                    .addComponent(exitButton)
                    .addComponent(registerButton)
                    .addComponent(logoutButton)
                    .addComponent(addModeratorButton)
                    .addComponent(removeModeratorButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(msgPopUpPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(mainForumPane, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addComponent(totalMsgsButton)
                        .addGap(36, 36, 36)
                        .addComponent(changeAdminButton)
                        .addGap(27, 27, 27)
                        .addComponent(msgsForUserButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
                        .addComponent(numOfConnectionButton)
                        .addGap(32, 32, 32)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(goButton)
                        .addComponent(BackButton)
                        .addComponent(addThreadButton))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(viewButton)
                        .addComponent(addSubForumButton)
                        .addComponent(removeSubForumButton)))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackButtonActionPerformed
      if (currentPath.size() >1)
      {
          currentPath.pop();
          Vector<String> path = currentPath.peek();
          int vectorSize = path.size();
          switch (vectorSize)
          {
              case 1:
                  this.createNewSenderThread(protocol.getViewSubForumMsg(userName, path));
                  break;
              case 2:
                  this.createNewSenderThread(protocol.getViewThreadMsg(userName, path));
                  break;
              default:
                  JOptionPane.showMessageDialog(this, "path size is not recognize the size is " + vectorSize, "error path", JOptionPane.ERROR);
          }
      }
      else
      {
          //TODO user roll
          currentPath.clear();
          this.createNewSenderThread(protocol.getViewForumMsg(this.userName));
      }
        
    }//GEN-LAST:event_BackButtonActionPerformed

    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
        loginOrRegisterPressed(true);
    }

    private void loginOrRegisterPressed(boolean isLogin) {
        LoginDiallog loginWindow = new LoginDiallog(this, true);
        if (loginWindow.getOKFlag())
        {
           tempUserName = loginWindow.getUserName();
           String password = loginWindow.getPassword();
           String msg ;
           if (isLogin)
           {
                
                msg = protocol.getLoginMsg(tempUserName, password);
           }
           else
           {
               msg = protocol.getRegisterMsg(tempUserName, password);
           }
            createNewSenderThread(msg);
        }
    }//GEN-LAST:event_loginButtonActionPerformed

    private void logoutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logoutButtonActionPerformed
        String msg = protocol.getLogoutMsg(this.userName);
        changeFromMemberToGuest();
        createNewSenderThread(msg);
        refreshMainWindow();
    }

    public void refreshMainWindow() {
        currentPath.push(new Vector<String>()); //to cheat back button;
        this.BackButtonActionPerformed(null);
    }//GEN-LAST:event_logoutButtonActionPerformed

    private void registerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registerButtonActionPerformed
         this.loginOrRegisterPressed(false);
     
    }//GEN-LAST:event_registerButtonActionPerformed

  
    public void refreshPopupMenu(Vector<GuiMessage> newMsg)
    {
        this.popupMsgs.addAll(newMsg);
        this.listPopupMsgs.setListData(popupMsgs);
    }
    
    
    private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goButtonActionPerformed
        GuiMessage selectedMsg = (GuiMessage)this.listOfObjects.getSelectedValue();
        if (selectedMsg != null)
        {
            switch (selectedMsg.getSubType())
            {
                case subForum :
                    sendViewSubForumMsg(selectedMsg);
                    break;
                case threadMsg:
                    sendViewThreadMsg(selectedMsg);
                    break;
                case postMsg:
                    openViwPostWindow(selectedMsg,isThread(this.listOfObjects.getSelectedIndex()));
                    break;
            }
        }
        else
        {
            JOptionPane.showMessageDialog(this, "you must select from the list", "error", JOptionPane.WARNING_MESSAGE);
        }
                
        
        
    }//GEN-LAST:event_goButtonActionPerformed

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        
        closeAllConnection();
        System.exit(0);
    }//GEN-LAST:event_exitButtonActionPerformed

    private void addThreadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addThreadButtonActionPerformed
       ViewPostMsg newMsg = new ViewPostMsg(this, true, null);
       newMsg.setVisible(true);
       if (newMsg.isEdited())
       {//add thread msg
           this.createNewSenderThread(protocol.getAddThreadMsg(userName, new Vector<String>(this.currentPath.peek()), newMsg.getSubject(), newMsg.getBody()));
       }
    }//GEN-LAST:event_addThreadButtonActionPerformed

    private void viewButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewButtonActionPerformed
    GuiMessage selectedMsg = (GuiMessage)this.listPopupMsgs.getSelectedValue();
    if (selectedMsg != null)
    {
        ViewPostMsg postMsg = new ViewPostMsg(this, true, selectedMsg);
        postMsg.setVisible(true);
    }
        
        
        // TODO add your handling code here:
    }//GEN-LAST:event_viewButtonActionPerformed

    private void addModeratorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addModeratorButtonActionPerformed
       boolean isAdd = true;
        createAddOrRemoveModerator(isAdd);
    }//GEN-LAST:event_addModeratorButtonActionPerformed

    private void removeModeratorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeModeratorButtonActionPerformed
        boolean isAdd = false;
        createAddOrRemoveModerator(isAdd);
    }//GEN-LAST:event_removeModeratorButtonActionPerformed

    private void addSubForumButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addSubForumButtonActionPerformed
        AddNewSubForum newSubForum = new AddNewSubForum(this, true);
        newSubForum.setVisible(true);
        if (newSubForum.isOk())
        {
            this.createNewSenderThread(this.protocol.getAddSubForum(userName, newSubForum.getSubForumName()));
        }
    }//GEN-LAST:event_addSubForumButtonActionPerformed

    private void removeSubForumButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeSubForumButtonActionPerformed
         GuiMessage selectedMsg = (GuiMessage)this.listOfObjects.getSelectedValue();
        if (selectedMsg != null)
        {
            this.createNewSenderThread(protocol.getRemoveSubForum(userName, selectedMsg.getMessageId()));
        }
        else
        {
            JOptionPane.showMessageDialog(this, "you must select from the list", "error", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_removeSubForumButtonActionPerformed

    private void totalMsgsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_totalMsgsButtonActionPerformed
      
         GuiMessage msg = (GuiMessage)this.listOfObjects.getSelectedValue();
       if (msg != null)
       {
            Vector<String> path = new Vector<String>();
            path.add(msg.getMessageId());
            this.createNewSenderThread(protocol.getNumOfMessagesInSubForum(userName, path));
       }
       else
       {
            JOptionPane.showMessageDialog(this, "you must select from the list", "error", JOptionPane.WARNING_MESSAGE);
       }
        
        
    }//GEN-LAST:event_totalMsgsButtonActionPerformed

    private void msgsForUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_msgsForUserButtonActionPerformed
        this.createNewSenderThread(protocol.getNumOfMessageByUser(userName));
    }//GEN-LAST:event_msgsForUserButtonActionPerformed

    private void listOfObjectsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listOfObjectsMouseClicked
        if (isDoubleClick(evt))
        {
            this.goButtonActionPerformed(null);
        }
    }//GEN-LAST:event_listOfObjectsMouseClicked

    private void listPopupMsgsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listPopupMsgsMouseClicked
        if (isDoubleClick(evt))
        {
            this.viewButtonActionPerformed(null);
        }
    }//GEN-LAST:event_listPopupMsgsMouseClicked

    private void changeAdminButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeAdminButtonActionPerformed
       this.createNewSenderThread(protocol.getAdminsCandidateList(this.userName));
    }//GEN-LAST:event_changeAdminButtonActionPerformed

    private void numOfConnectionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_numOfConnectionButtonActionPerformed
      this.createNewSenderThread(protocol.getNumOfConnection(userName));
    }//GEN-LAST:event_numOfConnectionButtonActionPerformed

    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /*
//         * Set the Nimbus look and feel
//         */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /*
//         * If Nimbus (introduced in Java SE 6) is not available, stay with the
//         * default look and feel. For details see
//         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(Forum.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(Forum.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(Forum.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(Forum.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /*
//         * Create and display the form
//         */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new Forum().setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BackButton;
    private javax.swing.JButton addModeratorButton;
    private javax.swing.JButton addSubForumButton;
    private javax.swing.JButton addThreadButton;
    private javax.swing.JButton changeAdminButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JButton goButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList listOfObjects;
    private javax.swing.JList listPopupMsgs;
    private javax.swing.JButton loginButton;
    private javax.swing.JButton logoutButton;
    private java.awt.ScrollPane mainForumPane;
    private java.awt.ScrollPane msgPopUpPane;
    private javax.swing.JButton msgsForUserButton;
    private javax.swing.JButton numOfConnectionButton;
    private javax.swing.JButton registerButton;
    private javax.swing.JToggleButton removeModeratorButton;
    private javax.swing.JButton removeSubForumButton;
    private javax.swing.JButton totalMsgsButton;
    private javax.swing.JButton viewButton;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
  
    private Vector<GuiMessage> forumMsgsMainPane;
    private Vector<GuiMessage> popupMsgs;
    private Stack<Vector<String>> currentPath;
    private  boolean isGuest;
    private  CreateMsgToServer protocol;
    private TelnetClient sendMsgToServer;
    private String userName;
    private void closeAllConnection() {
        this.createNewSenderThread(protocol.exit(userName));
    }

    void setForumMsgs(Vector<GuiMsg> newMsgs) {
        if (newMsgs != null)
        {
            this.listOfObjects.setListData(newMsgs);
        }
        
    }

    private void sendViewSubForumMsg(GuiMessage selectedMsg) {
        Vector<String> path = new Vector<String>();
        path.add(selectedMsg.getMessageId());
        currentPath.add(path);
        this.createNewSenderThread(protocol.getViewSubForumMsg(userName, path));
    }

    private void sendViewThreadMsg(GuiMessage selectedMsg) {
        if (!currentPath.isEmpty())
        {
            Vector<String> path = new Vector(currentPath.peek());
            path.add(selectedMsg.getMessageId());
            currentPath.add(path);
            this.createNewSenderThread(protocol.getViewThreadMsg(userName, path));
        }
        else
        {
            JOptionPane.showMessageDialog(this, "error stack is empty", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void openViwPostWindow(GuiMessage selectedMsg,boolean isThread) {
        
        ViewPostMsg msg = new ViewPostMsg(this, true, selectedMsg);
        msg.setVisible(true);
        Reply reply = msg.getReply();
        Vector<String> path = new Vector<String>(currentPath.peek());
        if (msg.isDeleted())
        {
            path.add(selectedMsg.getMessageId());
            this.createNewSenderThread(protocol.getDeleteMsg(userName, path,isThread));
        }
        else if(msg.isEdited())
        {
            path.add(selectedMsg.getMessageId());
            this.createNewSenderThread(protocol.getEditMsg(userName, path,msg.getSubject(),msg.getBody(),isThread));
        }
        else if (reply != null && reply.isSend())
        {
            path.add(selectedMsg.getMessageId());
            System.out.println(path);
            this.createNewSenderThread(protocol.getAddPostdMsg(userName, path, reply.getSubject(), reply.getBody(),isThread));
        }
    }

    void showAckMsg(GuiMessage msg) {
        switch (msg.getSubType())
        {
            case loginAck : case registerAck:
               isGuest = !checkIfSuccess(msg);
                if (!isGuest)
                {
                    this.changeLookFromGuestToMember();
                    updateButtons(this.forumMsgsMainPane);
                    this.userName = this.tempUserName;
                }
                break;
        }
       refresh(msg.getSubType());
       
        JOptionPane.showMessageDialog(this,msg.getBody() ,msg.getTitle() ,JOptionPane.INFORMATION_MESSAGE);
    }

  

    void updateMainWindow(Vector<GuiMessage> msgs) {
        this.forumMsgsMainPane = msgs;
         this.listOfObjects.setListData(msgs);
        updateButtons(msgs);
        
    }
    
    private void updateButtons(Vector<GuiMessage> msgs)
    {
        if (msgs.size()>0)
         {
             GuiMessage msg = msgs.firstElement();
             if (msg.getSubType() == GuiMessage.MessageSubType.threadMsg && !isGuest)
             {
                 this.addThreadButton.setVisible(true);
             }
             else
             {
                 this.addThreadButton.setVisible(false);
             }
             if (msg.getSubType() == GuiMessage.MessageSubType.subForum && msg.getAuthorization() == GuiMessage.MessageAuthorization.admin )
            {
                this.addModeratorButton.setVisible(true);
                this.msgsForUserButton.setVisible(true);
                this.totalMsgsButton.setVisible(true);
                this.changeAdminButton.setVisible(true);
                this.numOfConnectionButton.setVisible(true);
                this.removeModeratorButton.setVisible(true);
                this.addSubForumButton.setVisible(true);
                this.removeSubForumButton.setVisible(true);
                this.numOfConnectionButton.setVisible(true);
            }
             else
             {
                 this.addModeratorButton.setVisible(false);
                this.removeModeratorButton.setVisible(false);
                this.addSubForumButton.setVisible(false);
                this.removeSubForumButton.setVisible(false);
                 this.msgsForUserButton.setVisible(false);
                this.totalMsgsButton.setVisible(false);
                this.changeAdminButton.setVisible(false);
                this.numOfConnectionButton.setVisible(false);
             }
         } 
    }
    


    void showCandidateList(Vector<GuiMessage> msgs,GuiMessage.MessageSubType msgSubType) {
                GuiMessage first = msgs.elementAt(0);
                if (first.getType() == GuiMessage.MessageType.ack)
                    msgs.removeElementAt(0);
                ModeratorWindow moderatorWindow = new ModeratorWindow(this, true,msgSubType, msgs);
                moderatorWindow.setVisible(true);
                String moderatorName = moderatorWindow.getSelectedOne();
                Vector<String> path = new Vector<String>();
                 GuiMessage msg = (GuiMessage)this.listOfObjects.getSelectedValue();
                 if (moderatorName != null && !moderatorName.equals(""))
                 {
                        
                        switch (msgSubType)
                        {
                            case candidateList:
                                path.add(msg.getMessageId());
                                this.createNewSenderThread(protocol.getAddModeratorMsg(userName, moderatorName,path ));
                                break;
                            case moderatorList:
                                path.add(msg.getMessageId());
                                this.createNewSenderThread(protocol.getRemoveModerator(userName, moderatorName, path));
                                break;
                            case usersList:
                                  this.createNewSenderThread(protocol.getMsgCount(userName, moderatorName));
                                break;
                            case adminList:
                                this.createNewSenderThread(protocol.getChangeAdmin(userName,moderatorName));
                                break;
                        }
                 }
    }

    private boolean checkIfSuccess(GuiMessage msg) {
        return  msg.getBody().contains("success");
    }

    private void refresh(GuiMessage.MessageSubType subType) {
        if (needToRefresh(subType))
        {
            refreshMainWindow();
        }
        else
        {
              this.BackButtonActionPerformed(null);
        }
    }

    public void doBack() {
        this.BackButtonActionPerformed(null);
    }

    private boolean isDoubleClick(MouseEvent evt) {
        return evt.getClickCount() ==2;
    }

    private boolean needToRefresh(MessageSubType subType) {
        return subType != GuiMessage.MessageSubType.msgDeleted && subType != GuiMessage.MessageSubType.pathNotFound;
    }

    private boolean isThread(int selectedIndex) {
       return selectedIndex==0;
    }
    
}
